import json

from flask import Blueprint, request, jsonify, render_template
from apps.service.UserService import UserService

user = Blueprint('user', __name__, url_prefix='/user')



@user.route('/tolist', methods=['GET'])
def to_list():
    return render_template('user/list.html')



@user.route('/list', methods=['GET'])
def get_all_users():
    param = request.args
    data = UserService.get_all_users()
    return json.dumps(data)
    # return jsonify(data)

@user.route('/add', methods=['POST'])
def create_user():
    username = request.json['username']
    password = request.json['password']
    user = UserService.create_user(username, password)
    return jsonify(user)



@user.route('/find/int:user_id>', methods=['GET'])
def get_user(user_id):
    user = UserService.get_user_by_id(user_id)
    return jsonify(user)


@user.route('/update/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    new_username = request.json['username']
    user = UserService.update_user(user_id, new_username)
    return jsonify(user)


@user.route('/delete/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    UserService.delete_user(user_id)
    return '', 204
